package com.xz.purchase.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.annotation.DataScope;
import com.xz.product.domain.ProductCategory;
import com.xz.product.mapper.ProductCategoryMapper;
import com.xz.purchase.vo.ChoosePurchaseProductVo;
import com.xz.purchase.vo.ProductVo;
import com.xz.repertory.domain.RepertoryFlow;
import com.xz.supplierContract.domain.SupplierContract;
import com.xz.supplierContract.service.ISupplierContractService;
import com.xz.warehouse.domain.Warehouse;
import com.xz.warehouse.dto.WarehouseDto;
import com.xz.warehouse.service.IWarehouseService;
import com.xz.supplierContract.domain.SupplierContractPriceScheme;
import com.xz.supplierContract.service.ISupplierContractPriceSchemeService;
import com.xz.supplierContract.vo.SupplierContractPriceSchemeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.purchase.mapper.PurchaseProductMapper;
import com.xz.purchase.domain.PurchaseProduct;
import com.xz.purchase.service.IPurchaseProductService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 采购商品明细Service业务层处理
 *
 * @author xz
 * @date 2024-01-06
 */
@Service
public class PurchaseProductServiceImpl extends ServiceImpl<PurchaseProductMapper, PurchaseProduct> implements IPurchaseProductService {
    @Autowired
    private PurchaseProductMapper purchaseProductMapper;
    @Resource
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private ISupplierContractPriceSchemeService supplierContractPriceSchemeService;

    /**
     * 查询采购商品明细
     *
     * @param id 采购商品明细主键
     * @return 采购商品明细
     */
    @Override
    public PurchaseProduct selectPurchaseProductById(Long id) {
        return purchaseProductMapper.selectPurchaseProductById(id);
    }

    /**
     * 查询采购商品明细列表
     *
     * @param purchaseProduct 采购商品明细
     * @return 采购商品明细
     */
    @Override
    public List<PurchaseProduct> selectPurchaseProductList(PurchaseProduct purchaseProduct) {
        return purchaseProductMapper.selectPurchaseProductList(purchaseProduct);
    }

    /**
     * 新增采购商品明细
     *
     * @param purchaseProduct 采购商品明细
     * @return 结果
     */
    @Override
    public int insertPurchaseProduct(PurchaseProduct purchaseProduct) {
        return purchaseProductMapper.insertPurchaseProduct(purchaseProduct);
    }

    /**
     * 修改采购商品明细
     *
     * @param purchaseProduct 采购商品明细
     * @return 结果
     */
    @Override
    public int updatePurchaseProduct(PurchaseProduct purchaseProduct) {
        return purchaseProductMapper.updatePurchaseProduct(purchaseProduct);
    }

    /**
     * 批量删除采购商品明细
     *
     * @param ids 需要删除的采购商品明细主键
     * @return 结果
     */
    @Override
    public int deletePurchaseProductByIds(Long[] ids) {
        return purchaseProductMapper.deletePurchaseProductByIds(ids);
    }

    /**
     * 删除采购商品明细信息
     *
     * @param id 采购商品明细主键
     * @return 结果
     */
    @Override
    public int deletePurchaseProductById(Long id) {
        return purchaseProductMapper.deletePurchaseProductById(id);
    }

    /**
     * 冲红
     * @param idList
     * @return
     */
    @Override
    public int blush(List<Long> idList) {
        return purchaseProductMapper.blush(idList);
    }

    @Override
    public PurchaseProduct getPurchaseProductInfo(Long id) {
        return purchaseProductMapper.getPurchaseProductInfo(id);
    }

    @Override
    public int updateCostPrice(RepertoryFlow repertoryFlow) {
        return baseMapper.updateCostPrice(repertoryFlow);
    }

    @Override
    public Long selectPurchaseId(RepertoryFlow repertoryFlow) {
        return baseMapper.selectPurchaseId(repertoryFlow);
    }

    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<ProductVo> chooseProductList(PurchaseProduct purchaseProduct){

        List<ProductVo> productVos = baseMapper.chooseProduct(purchaseProduct);
        if(CollectionUtil.isNotEmpty(productVos)){
            // 开始查询商品库存
            productVos.stream().forEach(o->{
                purchaseProduct.setProductName(o.getProductName());
                purchaseProduct.setProductParam(o.getProductParam());
                purchaseProduct.setWarehouseId(purchaseProduct.getWarehouseId());
                Integer isMake = 1;
                if(o.getCategoryId()!=null) {
                    ProductCategory productCategory = productCategoryMapper.selectById(o.getCategoryId());
                    if (Objects.nonNull(productCategory)) {
                        isMake = productCategory.getIsMake() == null ? 1 : productCategory.getIsMake();
                    }
                }
                List<ChoosePurchaseProductVo> findList = baseMapper.findByNameAndParam(purchaseProduct);
                if(!CollectionUtil.isEmpty(findList)){
                    findList=findList.stream().filter(i->i.getAvailableStock()>0).collect(Collectors.toList());
                }
                final Integer isMakeValue = isMake;
                findList.forEach(s->{
                    s.setIsMake(isMakeValue);
                    s.setCategoryId(o.getCategoryId());
                });
                o.setPurchaseProductList(findList);
            });
        }
        return productVos;
    }


    /**
     * 销售新增商品专用
     * @param purchaseProduct
     * @return
     */
    @Override
    public List<ProductVo> choosePurchaseProductList(PurchaseProduct purchaseProduct){

        List<ProductVo> productVos = baseMapper.chooseSalesProduct(purchaseProduct);
        if(CollectionUtil.isNotEmpty(productVos)){
          productVos.stream().forEach(o->{
                purchaseProduct.setProductName(o.getProductName());
                purchaseProduct.setProductParam(o.getProductParam());
                purchaseProduct.setWarehouseId(purchaseProduct.getWarehouseId());
                Integer isMake = 1;
                if(o.getCategoryId()!=null) {
                    ProductCategory productCategory = productCategoryMapper.selectById(o.getCategoryId());
                    if (Objects.nonNull(productCategory)) {
                        isMake = productCategory.getIsMake() == null ? 1 : productCategory.getIsMake();
                    }
                }
                List<ChoosePurchaseProductVo> findList = baseMapper.findByNameAndParam(purchaseProduct);
                final Integer isMakeValue = isMake;
                findList.forEach(s->{
                    s.setIsMake(isMakeValue);
                    s.setCategoryId(o.getCategoryId());
                });
                o.setPurchaseProductList(findList);
            });
        }
        return productVos;
    }

    @DataScope(deptAlias = "d", userAlias = "u")
    @Override
    public List<PurchaseProduct> validityProductList(PurchaseProduct purchaseProduct){
        return baseMapper.validityProductList(purchaseProduct);
    }

  @Override
  public List<PurchaseProduct> getListByParam(PurchaseProduct purchaseProduct) {
    return baseMapper.getListByParam(purchaseProduct);
  }

  @DataScope(deptAlias = "d", userAlias = "u")
  @Override
  public List<ProductVo> chooseProductListForSupplier(PurchaseProduct purchaseProduct){

    List<ProductVo> productVos = baseMapper.chooseProduct(purchaseProduct);
    if(CollectionUtil.isNotEmpty(productVos)){
      // 开始获取贸易中间商的合同价格方案，返回以产品ID为key，价格方案实体为value的对象。
      Map<Long, SupplierContractPriceSchemeVo> contractPriceSchemeMap = supplierContractPriceSchemeService.selectByCurrnet(purchaseProduct.getEntSupplierId());
      // 开始查询商品库存
      productVos.stream().forEach(o->{
        purchaseProduct.setProductName(o.getProductName());
        purchaseProduct.setProductParam(o.getProductParam());
        purchaseProduct.setWarehouseId(purchaseProduct.getWarehouseId());
        Integer isMake = 1;
        if(o.getCategoryId()!=null) {
          ProductCategory productCategory = productCategoryMapper.selectById(o.getCategoryId());
          if (Objects.nonNull(productCategory)) {
            isMake = productCategory.getIsMake() == null ? 1 : productCategory.getIsMake();
          }
        }
        List<ChoosePurchaseProductVo> findList = baseMapper.findByNameAndParam(purchaseProduct);
        if(!CollectionUtil.isEmpty(findList)){
          findList=findList.stream().filter(i->i.getAvailableStock()>0).collect(Collectors.toList());
        }
        final Integer isMakeValue = isMake;
        findList.forEach(s->{
          s.setIsMake(isMakeValue);
          s.setCategoryId(o.getCategoryId());
          // 填充贸易中间商的合同价格字段，如果合同价格不存在，则填充商品原本价格。
          if(!CollectionUtils.isEmpty(contractPriceSchemeMap)){
            SupplierContractPriceSchemeVo contractPrice = contractPriceSchemeMap.get(s.getProductId());
            BigDecimal price = null != contractPrice ? contractPrice.getContractPrice() : s.getPrice();
            s.setSupllierContractPrice(price);
          }
        });
        o.setPurchaseProductList(findList);
      });
    }
    return productVos;
  }

  /**
   * 诊疗开单新增药品专用
   * @param purchaseProduct
   * @return
   */
  @DataScope(deptAlias = "d", userAlias = "u")
  @Override
  public List<ChoosePurchaseProductVo> chooseProductForDiagnosisae(PurchaseProduct purchaseProduct){
   return purchaseProductMapper.chooseProductForDiagnosisae(purchaseProduct);
  }
}
